package com.chuanke.ckfamily.action.common;

import com.chuanke.ckfamily.action.BaseController;
import com.chuanke.ckfamily.action.base.Response;
import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.service.base.FailCode;
import com.chuanke.ckfamily.service.common.RSAService;
import com.chuanke.ckfamily.service.common.TokenService;
import com.chuanke.ckfamily.service.common.model.UserToken;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.user.UserService;
import com.weijie.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wangbin on 2017/6/27.
 */
@Controller
@RequestMapping("/api/token")
public class TokenController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RSAService rsaService;

    @Autowired
    private UserService userService;

    @RequestMapping("/publicKey")
    @ResponseBody
    public Response getPublicKey() {
        return new Response(rsaService.getPublicKey());
    }

    @RequestMapping("/refresh")
    @ResponseBody
    public Response refreshToken(@RequestParam("token") String token) {
        String destToken = rsaService.decrypt(token);
        if (StringUtils.isEmpty(destToken)) {
            return new Response(FailCode.DECRYPTERROR, "解密失败");
        }

        try {
            UserToken userToken = tokenService.getUserToken(destToken);
            if (userToken == null) {
                logger.debug("token is null token={}", destToken);
                return new Response(FailCode.INVALITOKEN, "无效token");
            }

            User user = userService.findById(userToken.getId());
            if (user == null || !userToken.isInvalidate() || !user.getToken().equals(userToken.getToken())) {
                logger.debug("token is not equals send token={}, userTOken = {}", destToken, user.getToken());
                return new Response(FailCode.INVALITOKEN, "无效token");
            }

            return new Response(tokenService.createToken(userToken, true));

        } catch (CFException e) {
            e.printStackTrace();
            return new Response(e);

        } catch (Exception e) {
            e.printStackTrace();
            return new Response(FailCode.APP, e.getMessage());

        }
    }
}
